package org.funtester.performance.books.chapter05.section4;

import org.funtester.performance.books.chapter05.sectioin2.JavaWebSocketClient;
import org.java_websocket.enums.ReadyState;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Java-WebSocket客户端保活在性能测试中实践
 */
public class JavaWebsocketKeepAlive {

    public static void main(String[] args) throws URISyntaxException {
        String url = "ws://localhost:12345/websocket";// 服务端地址
        URI uri = new URI(url);// 转换为URI
        List<JavaWebSocketClient> clients = new ArrayList<>();// 存储 WebSocket 客户端
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(10000);// 10秒发送一次心跳
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for (JavaWebSocketClient client : clients) {
                    if (client.getReadyState() == ReadyState.OPEN) {// 判断是否连接
                        client.sendPing();// 发送心跳
                    }
                }
            }
        }).start();// 启动心跳线程
        for (int i = 0; i < 1000; i++) {
            Map<Integer, String> requestParams = new ConcurrentHashMap<>();
            JavaWebSocketClient client = new JavaWebSocketClient(uri) {

                @Override
                public void onMessage(String s) {
                    // 这里忽略响应处理,只保持连接
                }
            };// 创建 WebSocket 客户端
            client.connect();
            clients.add(client);// 存储客户端
        }
        // 下面开始性能测试用例编写
    }

}
